#include "SimpleTriangle.h"
#include <glad/glad.h>
#include <iostream>
#include <vector>

SimpleTriangle::SimpleTriangle()
{
    this->vertices = {-0.5f, -0.5f, 0, 0.5f, -0.5f, 0, 0, 0.5f, 0};
}

void SimpleTriangle::prepareVAO()
{

    /**
    vertex buffer objects (VBO) 可以一次传送大量顶点数据到显存
    因为从cpu发送数据到显卡是比较慢的，所以希望一次搞定
    */
    // 创建一个VBO对象并给定其id
    unsigned int VBO;

    glGenBuffers(1, &VBO);

    // 创建 VBO 的 buffer type ( the buffer type of a vertex buffer object)
    glBindBuffer(GL_ARRAY_BUFFER, VBO);
    /*
    From that point on any buffer calls we make (on the GL_ARRAY_BUFFER target)
    will be used to configure the currently bound buffer, which is VBO.
    从此之后任何对于 GL_ARRAY_BUFFER 的调用都将用于配置当前绑定的
    buffer，也就是前面创建的 VBO
    */

    /*
    glBufferData is a function specifically targeted to copy user-defined data
    into the currently bound buffer.
    1、把顶点数据拷贝到 VBO 中
    */
    glBufferData(GL_ARRAY_BUFFER, this->vertices.size() * sizeof(float),
                 this->vertices.data(), GL_STATIC_DRAW);

    cout << "vertics size is " << this->vertices.size() << endl;
    /*
    2、Linking Vertex Attributes
    The vertex shader allows us to specify any input we want in the form of
    vertex attributes and while this allows for great flexibility, it does mean
    we have to manually specify what part of our input data goes to which vertex
    attribute in the vertex shader. This means we have to specify how OpenGL
    should interpret the vertex data before rendering.

    Each vertex attribute takes its data from memory managed by a VBO and which
    VBO it takes its data from (you can have multiple VBOs) is determined by the
    VBO currently bound to GL_ARRAY_BUFFER when calling glVertexAttribPointer.
    Since the previously defined VBO is still bound before calling
    glVertexAttribPointer vertex attribute 0 is now associated with its vertex
    data.
    */
    glVertexAttribPointer(
        0, // 我们想配置的哪个 vertex attribute，这里我们设置 location of vertex
           // attribute 为0，和顶点着色器源码中 layout (location = 0)  一致
        3, // 指定 vertex attribute 的大小，因为 vertex attribute 是  vec3
           // 三维向量，所以这里填3
        GL_FLOAT, // GLSL vec3 中的数据类型
        GL_FALSE, // 数据是否需要被规范化 [-1,1]之间
        3 * sizeof(
                float), // 指定  vertex attributes
                        // 的步长，因为输入的每一个顶点都是连续的，且每一个点是float类型，一个vertex是三维的，所以这里是12Bytes
        (void*)0        // position data 在 buffer 中的偏移量
    );

    /**
    3、glVertexAttribPointer 是设置状态
    而 glEnableVertexAttribArray 是 使能 glVertexAttribPointer 的设置
     */
    glEnableVertexAttribArray(
        0); // 参数是指定要使能哪一个 vertex attribute location

    // 4、use our shader program when we want to render an object
    // glUseProgram(shaderProgram);
}

void SimpleTriangle::render()
{

    glDrawArrays(GL_TRIANGLES, 0, 3);

    //cout << "draw triangle" << endl;
}